/*Copyright (c) 2011 Samuel Madden
 
 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 */
//
//  ExtractApertureFacesAppDelegate.m
//  ExtractApertureFaces
//
//  Created by Samuel Madden on 9/23/11.
//

#import "ExtractApertureFacesAppDelegate.h"

@implementation ExtractApertureFacesAppDelegate

@synthesize window, nameToExtract, status, pathField, photoCountField, progress;

#define AP_DIRECTORY @"Aperture Library.aplibrary"
#define MAIN_APERTURE_LIBRARY @"Database/apdb/Library.apdb" 
#define FACES_LIBRARY @"Database/apdb/Faces.db" 
#define PREVIEWS_DIRECTORY @"Previews" 



- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSPicturesDirectory,
                                                         NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *dbPath = [docDir stringByAppendingPathComponent:AP_DIRECTORY];
    [self setApertureLibraryPath:dbPath];
    nameToExtract->completeDelegate = self;
}

-(IBAction) hitChangeLibraryButton:(id)sender {
    NSOpenPanel * panel = [NSOpenPanel openPanel];
    [panel setMessage:@"Select an aperture library (apLibrary file)."];
    [panel setCanChooseDirectories:NO];
    [panel setCanChooseFiles:YES];
    [panel setAllowsMultipleSelection:NO];
    [panel setCanCreateDirectories:YES];
    [panel setAllowedFileTypes:[NSArray arrayWithObject:@"aplibrary"]];
    [panel beginSheetModalForWindow:window completionHandler:^(NSInteger returnCode)
    {
        if (returnCode == NSOKButton) {
            NSURL *url = [[panel URLs] objectAtIndex:0];
            [self setApertureLibraryPath: [url path]];
        }
    }];

}



-(void) runCommandOnFiles:(SEL)selector msg:(NSString *)msg askUserForFileName:(BOOL)askUserForFileName {
    if ([[nameToExtract string] length] == 0) {
        NSAlert *alert = [[NSAlert alloc] init];
        [alert setMessageText:@"Missing Name"];
        [alert setInformativeText:@"You must enter the name of a person whose photos you would like to extract."];
        [alert runModal];
        [alert release];
        return;
        
    }
    
    
    if (!isValid) {
        NSAlert *alert = [[NSAlert alloc] init];
        [alert setMessageText:@"Invalid Photo Library"];
        [alert setInformativeText:@"You must select a valid photo library to extract images from."];
        [alert runModal];
        [alert release];
        return;
        
    }
    
    if ([self countFilesForCurName] ==0) {
        NSAlert *alert = [[NSAlert alloc] init];
        [alert setMessageText:@"No Photos"];
        [alert setInformativeText:@"The selected library contains no photos of the person you named."];
        [alert runModal];
        [alert release];
        return;
    }
    
    NSSavePanel *panel;
    if (askUserForFileName) {
        panel = [NSSavePanel savePanel];
        [panel setAllowedFileTypes:[NSArray arrayWithObject:@"pdf"]];

    } else {
        panel = [NSOpenPanel openPanel];
        [(NSOpenPanel *)panel setCanChooseDirectories:YES];
        [(NSOpenPanel *)panel setCanChooseFiles:NO];
        [(NSOpenPanel *)panel setAllowsMultipleSelection:NO];

    }
    [panel setMessage:msg];
    [panel setCanCreateDirectories:YES];
    //[panel setAllowedFileTypes:[NSArray arrayWithObject:@"aplibrary"]];
    [panel beginSheetModalForWindow:window completionHandler:^(NSInteger returnCode)
     {
         if (returnCode == NSOKButton) {

             NSURL *url = [panel URL];
             [NSThread detachNewThreadSelector:selector toTarget:self withObject:[[url path] retain]];
         }
     }];
}



-(void) findFilesAndSaveToPath:(NSString*) path {
    NSArray *files = [self getPhotoFilesForName:[nameToExtract string]];
    
    [self saveFilesToPath:path files:files];
    
}

-(IBAction) hitDoExtractImages:(id)sender {
    [self runCommandOnFiles:@selector(findFilesAndSaveToPath:) 
                        msg:@"Select a destination for the extracted images."
      askUserForFileName:NO];
}




-(void) makeBigImageWithFiles:(NSString *)path files:(NSArray *)filePaths {
    int imgWidth = 50;
    int numCols = sqrt([filePaths count]);
    int numRows = ((int)[filePaths count])/numCols;
    int curRow = 0, curCol = 0;
    int cnt = 0;
    [progress setIndeterminate:NO];
    [progress setMaxValue:[filePaths count]];
    [progress startAnimation:self];
    [status setStringValue:[NSString stringWithFormat:@"Writing 1 of %d",[filePaths count]]];

    NSView *v = [[[NSView alloc]  initWithFrame:NSMakeRect(0, 0, numCols * imgWidth, numRows *imgWidth)] autorelease];

    for (NSString *s in filePaths) {
        NSImageView *i = [[[NSImageView alloc] initWithFrame:NSMakeRect(curCol*imgWidth, curRow*imgWidth, imgWidth,imgWidth)] autorelease];
        [i setImage:[[[NSImage alloc]  initWithContentsOfFile:s] autorelease]];
        [v addSubview:i];
        curCol++;
        if (curCol >= numCols) {
            curRow++;
            curCol = 0;
        }
        [status setStringValue:[NSString stringWithFormat:@"Writing %d of %d",++cnt,[filePaths count]]];
        [progress setDoubleValue:cnt];

    }
    NSData *data = [v dataWithPDFInsideRect:[v bounds]];
    [data writeToFile:path atomically:YES];
    
    [progress stopAnimation:self];
    [progress setDoubleValue:0];
    [status setStringValue:@"Finished extracting."];

}

-(void) findFilesAndSaveBigImage:(NSString*) path {
    NSArray *files = [self getPhotoFilesForName:[nameToExtract string]];
    
    [self makeBigImageWithFiles:path files:files];
    
}

-(IBAction) hitExtractLargeImageButton:(id)sender {
    [self runCommandOnFiles:@selector(findFilesAndSaveBigImage:) 
                        msg:@"Select a destination for the composite PDF image."
         askUserForFileName:YES];
}


-(void) saveFilesToPath:(NSString *)path files:(NSArray *)filePaths {
    int imgWidth = 200;
    int cnt = 0;
    [progress setIndeterminate:NO];
    [progress setMaxValue:[filePaths count]];
    [progress startAnimation:self];
    [status setStringValue:[NSString stringWithFormat:@"Writing 1 of %d",[filePaths count]]];
    
    NSImageView *i = [[[NSImageView alloc] initWithFrame:NSMakeRect(0,0, imgWidth,imgWidth)] autorelease];
    for (NSString *s in filePaths) {
        [i setImage:[[[NSImage alloc]  initWithContentsOfFile:s] autorelease]];
        [[i dataWithPDFInsideRect:[i bounds]] writeToFile:[NSString stringWithFormat:@"%@/img%d.pdf",path,cnt++] atomically:YES];
        [progress setDoubleValue:cnt];
        [status setStringValue:[NSString stringWithFormat:@"Writing %d of %d",cnt,[filePaths count]]];
    }
    [progress stopAnimation:self];
    [progress setDoubleValue:0];
    [status setStringValue:@"Finished extracting."];
}




-(void) setApertureLibraryPath:(NSString *)path {
    NSFileManager *m = [NSFileManager defaultManager];
    [status setTextColor:[NSColor redColor]];
    
    if (![m fileExistsAtPath:path]) {
        isValid = NO;
        [status setStringValue:@"No Aperture Library found."];
    }
    

    NSString *mainLibraryPath = [path stringByAppendingPathComponent:MAIN_APERTURE_LIBRARY];
    NSString *facesPath = [path stringByAppendingPathComponent:FACES_LIBRARY];
    
    mainLibraryDb = [[SQLiteIntf alloc] initWithDbPath:mainLibraryPath];
    facesDb = [[SQLiteIntf alloc] initWithDbPath:facesPath];
    previewPath = [[path stringByAppendingPathComponent:PREVIEWS_DIRECTORY] retain];
    
    [pathField setStringValue:path];
    
    if (![m fileExistsAtPath:mainLibraryPath] || ![m fileExistsAtPath:facesPath]) {
        isValid = NO;
        [status setStringValue:@"Selected library is invalid (does not contain faces.db or Library.apdb file)."];
    } else if (![facesDb tableExists:@"RKDetectedFace"] || ![facesDb tableExists:@"RKFaceName"] || ![mainLibraryDb tableExists:@"RKVersion"]) {
        [status setStringValue:@"Selected library is invalid (library missing one or more expected database tables)."];
        isValid = NO;
    } else {
        isValid = YES;
        [status setTextColor:[NSColor blackColor]];
        [status setStringValue:@"Ready to extract photos."];
    }
    
}


-(NSArray *)getCompletionList {
    NSString *name = [nameToExtract string];
    if (isValid) {
        NSArray *names = [facesDb runQuery:[NSString stringWithFormat:@"SELECT distinct name FROM RKDetectedFace AS a, RKFaceName AS b WHERE a.faceKey = b.faceKey AND name LIKE '%@%%'",name]];
        return names;
    } 
    return NULL;
}

-(int)countFilesForCurName {
    NSString *name = [nameToExtract string];
    if (isValid) {
        NSArray *names = [facesDb runQuery:[NSString stringWithFormat:@"SELECT count(*) FROM RKDetectedFace AS a, RKFaceName AS b WHERE a.faceKey = b.faceKey AND name = '%@'",name]];
        if ([names count]) {
            return [[names objectAtIndex:0] intValue];
        } 
    } 
    return 0;
    
}
        
        
-(void) curNameChanged {
    int count = [self countFilesForCurName];
    if (count > 0) {
        [photoCountField setStringValue:[NSString stringWithFormat:@"%d photos",count]];
    } else {
        [photoCountField setStringValue:[NSString stringWithFormat:@"No photos"]];
    }
}


-(NSArray *)getPhotoFilesForName:(NSString *)name {
    NSArray *uuidList = [self findPhotosForName:name];
    NSMutableDictionary *files = [[[NSMutableDictionary alloc] init] autorelease];
    for (NSArray *s in uuidList) {
        [files setObject:s forKey:[s objectAtIndex:0]];
    }
    NSArray *filePaths = [self findFilesInList:previewPath fileList:files];
    NSLog(@"GOT %u", (unsigned int)[filePaths count]);
    return filePaths;
    
}


static int cnt = 0;

-(NSArray *)findFilesInList:(NSString*)path fileList:(NSDictionary *)fileList first:(BOOL)first {
    NSString* file;
    NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:path];
    NSMutableArray *returnSet = [[[NSMutableArray alloc] init] autorelease];

    if (first) {
        [progress setUsesThreadedAnimation:YES];
        [progress setIndeterminate:YES];
        [progress startAnimation:self];
        [status setStringValue:@"Scanning Files"];
        cnt = 0;
    }
    while (file = [enumerator nextObject])
    {
        cnt++;
        //[progess animate:self];
        if (cnt % 1000 == 0)
            NSLog(@"cnt=%d",cnt);
        // check if it's a directory
        BOOL isDirectory = NO;
        NSString *newPath = [NSString stringWithFormat:@"%@/%@",path,file];
        [[NSFileManager defaultManager] fileExistsAtPath: newPath
                                             isDirectory: &isDirectory];
        if (isDirectory)
        {
            NSArray *list = [fileList objectForKey:file];
            if (list != NULL) {
                [returnSet addObject:[NSString stringWithFormat:@"%@/thumb_%@_face%@.jpg",newPath,
                                      [list objectAtIndex:1],[list objectAtIndex:2]]];
            } else {
                [returnSet addObjectsFromArray:[self findFilesInList: newPath fileList:fileList first:NO]];
            }
            [enumerator skipDescendants];
        } else {
        }
    }
    if (first) {
        [status setStringValue:@""];
        [progress stopAnimation:self];
    }
    return returnSet;
}

-(NSArray *)findFilesInList:(NSString*)path fileList:(NSDictionary *)fileList {
    return [self findFilesInList:path fileList:fileList first:YES];
}

-(NSArray *) findPhotosForName:(NSString *)name {

    NSArray *masterUUIDs = [facesDb runQuery:[NSString stringWithFormat:@"SELECT a.masterUuid,faceIndex FROM RKDetectedFace AS a, RKFaceName AS b WHERE a.faceKey = b.faceKey AND name = '%@'",name]];
    NSMutableArray *uuidList = [[[NSMutableArray alloc] init] autorelease];
    for (NSString *r in masterUUIDs) {
        NSArray *ar = [r componentsSeparatedByString:@"|"];
        //for each photo, find the UUID
        NSArray *result = [mainLibraryDb runQuery:[NSString stringWithFormat:@"SELECT uuid,name FROM RKVersion WHERE masterUuid = '%@'",[ar objectAtIndex:0]]];
        if ([result count] > 0) {
            NSArray *ar2 = [[result objectAtIndex:0] componentsSeparatedByString:@"|"];
            [uuidList addObject:[NSArray arrayWithObjects:[ar2 objectAtIndex:0],[ar2 objectAtIndex:1],[ar objectAtIndex:1],nil]];
        }
    }
    return uuidList;
}


@end
